package br.com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.connection.ConnectionFactory;
import br.com.controller.FuncaoController;

/**
 * Servlet implementation class FuncaoServlet
 */
@WebServlet("/FuncaoServlet")
public class FuncaoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FuncaoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		try{
			doInser(request, response);
		}catch (Exception e){
			out.println("ocorreu algum erro");
		}

	}

	protected void doInser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();

		request.setCharacterEncoding("UTF-8");        
		response.setCharacterEncoding("UTF-8");
		String funcao = request.getParameter("funcao");
		Connection conn = null;

		try {

			conn = new ConnectionFactory().getConnection();
			FuncaoController.inserir(conn, funcao);

			out.print("<script type=\"text/javascript\">	alert(\"Cadastrado com sucesso.\");</script>");

			conn.commit();

		} catch (Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (Exception ex) {ex.printStackTrace();}
		} finally {
			try {
				conn.close();
			} catch (Exception ex) {}
		} 

	}

}
